/**
 * 
 */
package com.heer.RD.projecthour.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.model.Model;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author ZhaoZehui
 *
 */
public class DeptChoice extends ListChoice {

	private Map<String, String> NAMES = new HashMap<String, String>();
	private List<String> deptIds = new ArrayList<String>();
	
	public DeptChoice(String id, JdbcTemplate jt, String deptId) {
		super(id);
		setMaxRows(1);
		setModel(new Model<String>());
		
		init(jt, deptId);
		
	}
	
	public void init(JdbcTemplate jt, String deptId) {
		NAMES.clear();
		deptIds.clear();
		
		String osql = "select dept_id,dept_name from department where dept_id = ?";
		String sql = "select dept_id,dept_name from department where father_id = ? order by dept_name";
		List<Map<String, String>> level1List = jt.queryForList(osql, new Object[]{deptId});
		for (Map<String, String> dept1 : level1List) {
			deptIds.add(dept1.get("DEPT_ID"));
			NAMES.put(dept1.get("DEPT_ID"), dept1.get("DEPT_NAME"));
			
			List<Map<String, String>> level2List = jt.queryForList(sql, new Object[]{dept1.get("DEPT_ID")});
			for (Map<String, String> dept2 : level2List) {
				deptIds.add(dept2.get("DEPT_ID"));
				NAMES.put(dept2.get("DEPT_ID"), "├──"+dept2.get("DEPT_NAME"));
				
				List<Map<String, String>> level3List = jt.queryForList(sql, new Object[]{dept2.get("DEPT_ID")});
				for (Map<String, String> dept3 : level3List) {
					deptIds.add(dept3.get("DEPT_ID"));
					NAMES.put(dept3.get("DEPT_ID"), "├──├──"+dept3.get("DEPT_NAME"));
					
					List<Map<String, String>> level4List = jt.queryForList(sql, new Object[]{dept3.get("DEPT_ID")});
					for (Map<String, String> dept4 : level4List) {
						deptIds.add(dept4.get("DEPT_ID"));
						NAMES.put(dept4.get("DEPT_ID"), "├──├──├──"+dept4.get("DEPT_NAME"));
						
					}
				}
			}
		}
		IChoiceRenderer render = new ChoiceRenderer() {
			public Object getDisplayValue(Object object) {
				return NAMES.get(object);
			}
			public String getIdValue(Object object, int index)	{
				if(index >= 0)
					return String.valueOf(deptIds.get(index));
				else
					return "";
			}
		};
		this.setChoices(deptIds);
		this.setChoiceRenderer(render);
	}
	
	public String getDeptName(String deptId) {
		String deptName = NAMES.get(deptId);
		deptName = StringUtils.replace(deptName, "─", "");
		deptName = StringUtils.replace(deptName, "├", "");
		return deptName;
	}

}
